package com.sk.sourcecircle.activity.home.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.google.zxing.WriterException;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.activity.home.fragment.OtherAlbumFragment;
import com.sk.sourcecircle.activity.home.fragment.OtherJoinedEventFragment;
import com.sk.sourcecircle.activity.login.LoginActivity;
import com.sk.sourcecircle.activity.mine.act.PersonlCodeActivity;
import com.sk.sourcecircle.activity.mine.act.PreviewViewpagerActivity;
import com.sk.sourcecircle.adapter.MyPagerAdapter;
import com.sk.sourcecircle.base.BaseActivity;
import com.sk.sourcecircle.callback.HandleDataCallBack;
import com.sk.sourcecircle.dialog.TipDialogFragment;
import com.sk.sourcecircle.entity.HomePageInfo;
import com.sk.sourcecircle.utils.AppApi;
import com.sk.sourcecircle.utils.MyUtils;
import com.sk.sourcecircle.utils.SnackUtils;
import com.sk.sourcecircle.view.NoticeView;
import com.sk.sourcecircle.view.StarBar;
import com.sk.sourcecircle.zxing.encoding.EncodingHandler;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by sk on 2017/12/14.
 */

public class PersonDetailsActivity extends BaseActivity implements HandleDataCallBack {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.pep_head)
    ImageView pepHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.add_care)
    TextView addCare;
    @BindView(R.id.cancel_care)
    TextView cancelCare;
    @BindView(R.id.des_star)
    StarBar desStar;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.tv_describe)
    TextView tvDescribe;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.friend_num)
    TextView friendNum;
    @BindView(R.id.friend_ll)
    LinearLayout friendLl;
    @BindView(R.id.care_num)
    TextView careNum;
    @BindView(R.id.care_ll)
    LinearLayout careLl;
    @BindView(R.id.album_num)
    TextView albumNum;
    @BindView(R.id.album_ll)
    LinearLayout albumLl;
    @BindView(R.id.my_table)
    TabLayout myTable;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.my_pager)
    ViewPager myPager;
    @BindView(R.id.care_l)
    FrameLayout careL;
    @BindView(R.id.qr_code)
    ImageView qrCode;
    @BindView(R.id.notice_view)
    NoticeView noticeView;

    private int user_id;
    private LoadingDialog loadingDialog;

    private OtherAlbumFragment otherAlbumFragment;
    private OtherJoinedEventFragment otherJoinedEventFragment;

    private List<Fragment> fragmentList = new ArrayList<>();
    private String name = "";
    private String url = "";

    public int getUser_id() {
        return user_id;
    }

    public void setUser_id(int user_id) {
        this.user_id = user_id;
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_person_details;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        noticeView.getNotice("-1");

        initFragments();
        user_id = getIntent().getIntExtra("id", 0);

        Bitmap mBitmap = null;
        try {
            mBitmap = EncodingHandler.createQRCode("type=1&id=" + user_id, 300);
            if (mBitmap != null) {
                Drawable drawable = new BitmapDrawable(mBitmap);
                qrCode.setBackground(drawable);
            }
        } catch (WriterException e) {
            e.printStackTrace();
        }

        loadingDialog = MyUtils.getLoadingDialog(mContext, false);
        loadingDialog.show();
        AppApi.otherPersonInfo(user_id, this, 0, this);
    }

    private void initFragments() {

        otherAlbumFragment = new OtherAlbumFragment();
        otherJoinedEventFragment = new OtherJoinedEventFragment();

        fragmentList.add(otherJoinedEventFragment);
        fragmentList.add(otherAlbumFragment);

        MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager(), getResources().getStringArray(R.array.pep_array), fragmentList);
        myPager.setAdapter(adapter);
        myTable.setupWithViewPager(myPager);
    }

    @OnClick({R.id.back, R.id.add_care, R.id.cancel_care,R.id.qr_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.add_care:
                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(intent, 100);
                    return;
                }
                loadingDialog.show();
                AppApi.addFriend(user_id, this, 1, this);
                break;
            case R.id.cancel_care:
                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(intent, 100);
                    return;
                }
                TipDialogFragment tipDialogFragment = new TipDialogFragment();
                tipDialogFragment.setMyCallBack(PersonDetailsActivity.this);
                tipDialogFragment.setContent("确认删除改好友嘛？");
                tipDialogFragment.show(getSupportFragmentManager(), "delete");
                break;
            case R.id.qr_code:
                Intent intent = new Intent(mContext, PersonlCodeActivity.class);
                intent.putExtra("type",1);
                intent.putExtra("string","type=1&id="+user_id);
                intent.putExtra("name",name);
                intent.putExtra("url",url);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        switch (tag) {
            case 0:
                HomePageInfo homePageInfo = JSON.parseObject(result, HomePageInfo.class);
                HomePageInfo.DataBean dataBean = homePageInfo.getData();
                Glide.with(mContext).load(dataBean.getUser_info().getHead_url()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(pepHead);
                final List<String> stringList = new ArrayList<>();
                stringList.add(dataBean.getUser_info().getHead_url());
                pepHead.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, PreviewViewpagerActivity.class);
                        Activity activity = (Activity) mContext;
                        intent.putExtra("pos", 0);
                        intent.putStringArrayListExtra("list", (ArrayList<String>) stringList);
                        activity.startActivity(intent);
                    }
                });
                tvName.setText(dataBean.getUser_info().getNickname());
                name = dataBean.getUser_info().getNickname();
                url = dataBean.getUser_info().getHead_url();
                desStar.setStarMark(dataBean.getUser_info().getSincerity());
                if (dataBean.getUser_info().getIntroduce() != null) {
                    tvDescribe.setText("简介："+dataBean.getUser_info().getIntroduce());
                }
                friendNum.setText(String.valueOf(dataBean.getFriend_count()));
                careNum.setText(String.valueOf(dataBean.getFollow_count()));
                albumNum.setText(String.valueOf(dataBean.getAlbum_count()));
                if(dataBean.getUser_info().getAddress()!=null){
                    tvLocation.setText("所在地："+dataBean.getUser_info().getAddress());
                }
                if (dataBean.getIs_friend() == 1) {
                    cancelCare.setVisibility(View.VISIBLE);
                    addCare.setVisibility(View.GONE);
                } else {
                    cancelCare.setVisibility(View.GONE);
                    addCare.setVisibility(View.VISIBLE);
                }
                break;
            case 1:
                SnackUtils.show(mRootView,"请求发送成功,等待对方回复！");
                break;
            case 2:
                SnackUtils.show(mRootView,"好友删除成功！");
                cancelCare.setVisibility(View.GONE);
                addCare.setVisibility(View.VISIBLE);
                break;
        }

    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void sure() {
        super.sure();
        AppApi.doFriend(user_id, 4, PersonDetailsActivity.this, 2, PersonDetailsActivity.this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == -1){
            if(requestCode == 100){
                loadingDialog.show();
                AppApi.otherPersonInfo(user_id, this, 0, this);
                otherAlbumFragment.reFresh();
            }
        }
    }
}
